import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, ScrollView, TextInput, Alert, RefreshControl, ActivityIndicator, Modal } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import AsyncStorage from '@react-native-async-storage/async-storage';

const BASE_URL = 'http://124.222.104.145:8003';

const PreferenceEdit = ({ navigation }) => {
    const [groupedTags, setGroupedTags] = useState({});
    const [selectedTags, setSelectedTags] = useState([]); // default_tags
    const [customTags, setCustomTags] = useState([]); // {id, name}
    const [customInput, setCustomInput] = useState('');
    const [refreshing, setRefreshing] = useState(false);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [showInput, setShowInput] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [isLogin, setIsLogin] = useState(true);

    // 获取所有分组标签
    const fetchGroupedTags = async () => {
        try {
            const res = await fetch(`${BASE_URL}/user/grouped-tags/`);
            const data = await res.json();
            setGroupedTags(data);
        } catch (e) {
            Alert.alert('错误', '获取标签失败');
        }
    };

    // 获取当前用户偏好
    const fetchUserPreference = async () => {
        try {
            const token = await AsyncStorage.getItem('authToken');
            if (token) {
                setIsLogin(true);
                const res = await fetch(`${BASE_URL}/user/preference/`, {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                const contentType = res.headers.get('content-type');
                if (contentType && contentType.indexOf('application/json') !== -1) {
                    const data = await res.json();
                    setSelectedTags(data.default_tags || []);
                    setCustomTags((data.tags || []).map(t => ({ id: t.id, name: t.name })));
                } else {
                    const text = await res.text();
                    console.error('接口返回非JSON:', text);
                    setIsLogin(false);
                }
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
            setIsLogin(false);
        }
    };

    // 刷新
    const onRefresh = useCallback(async () => {
        setRefreshing(true);
        await fetchGroupedTags();
        await fetchUserPreference();
        setRefreshing(false);
    }, []);

    useEffect(() => {
        (async () => {
            setLoading(true);
            await fetchGroupedTags();
            await fetchUserPreference();
            setLoading(false);
        })();
    }, []);

    // 选择/取消标签
    const toggleTag = (tag) => {
        setSelectedTags(prev => prev.includes(tag) ? prev.filter(t => t !== tag) : [...prev, tag]);
    };

    // 添加自定义标签
    const addCustomTag = () => {
        const name = customInput.trim();
        if (!name) return;
        if (customTags.some(t => t.name === name)) {
            Alert.alert('提示', '自定义标签已存在');
            return;
        }
        setCustomTags(prev => [...prev, { name }]);
        setCustomInput('');
    };

    // 删除自定义标签（仅本地新增的）
    const removeCustomTag = (name) => {
        setCustomTags(prev => prev.filter(t => t.name !== name));
    };

    // 保存
    const handleSave = async () => {
        setSaving(true);
        try {
            const token = await AsyncStorage.getItem('authToken');
            const custom_tag_names = customTags.map(t => t.name); // 只传 name
            const body = {
                default_tags: selectedTags,
                custom_tag_names
            };
            const res = await fetch(`${BASE_URL}/user/preference/`, {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(body)
            });
            const contentType = res.headers.get('content-type');
            if (contentType && contentType.indexOf('application/json') !== -1) {
                const data = await res.json();
                if (res.ok) {
                    Alert.alert('成功', '保存成功');
                    await fetchUserPreference(); // 关键：刷新本地 customTags
                } else {
                    Alert.alert('失败', data.detail || '保存失败');
                }
            } else {
                const text = await res.text();
                console.error('接口返回非JSON:', text);
                Alert.alert('错误', '保存失败');
            }
        } catch (e) {
            Alert.alert('错误', '保存失败');
        } finally {
            setSaving(false);
        }
    };

    if (loading) {
        return <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}><ActivityIndicator size="large" color="#70a1ff" /></View>;
    }

    return (
        <View style={styles.container}>
            {/* 顶部栏 */}
            <View style={styles.header}>
                <TouchableOpacity onPress={() => navigation.goBack()}>
                    <Icon name="angle-left" size={28} color="#333" />
                </TouchableOpacity>
                <Text style={styles.headerTitle}>个人偏好</Text>
                <View style={{ width: 28 }} />
            </View>
            <ScrollView
                style={{ flex: 1 }}
                refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#4CAF50']} />}
            >
                {/* 标签分组区 */}
                {Object.entries(groupedTags).map(([group, subgroups]) => (
                    <View key={group} style={styles.groupBlock}>
                        <Text style={styles.groupTitle}>{group}</Text>
                        {Object.entries(subgroups).map(([sub, tags]) => (
                            <View key={sub} style={styles.subgroupBlock}>
                                <Text style={styles.subTitle}>{sub}</Text>
                                <View style={styles.tagList}>
                                    {tags.map(tag => (
                                        <TouchableOpacity
                                            key={tag}
                                            style={[styles.tag, selectedTags.includes(tag) && styles.tagSelected]}
                                            onPress={() => toggleTag(tag)}
                                        >
                                            <Text style={[styles.tagText, selectedTags.includes(tag) && styles.tagTextSelected]}>{tag}</Text>
                                        </TouchableOpacity>
                                    ))}
                                </View>
                            </View>
                        ))}
                    </View>
                ))}
                {/* 已选自定义标签区 */}
                <View style={styles.groupBlock}>
                    <Text style={styles.groupTitle}>自定义标签</Text>
                    <View style={styles.tagList}>
                        {customTags.map(tag => (
                            <View key={tag.name} style={styles.customTag}>
                                <Text style={styles.customTagText}>{tag.name}</Text>
                                <TouchableOpacity onPress={() => removeCustomTag(tag.name)}>
                                    <Icon name="times-circle" size={16} color="#d9534f" style={{ marginLeft: 4 }} />
                                </TouchableOpacity>
                            </View>
                        ))}
                        {showInput ? (
                            <View style={styles.addTagInputRow}>
                                <TextInput
                                    style={styles.addTagInputNew}
                                    placeholder="输入自定义标签"
                                    value={customInput}
                                    onChangeText={setCustomInput}
                                    autoFocus
                                    onBlur={() => setShowInput(false)}
                                />
                                <TouchableOpacity
                                    onPress={() => {
                                        if (customInput.trim()) {
                                            addCustomTag();
                                            setShowInput(false);
                                        }
                                    }}
                                    style={styles.addTagConfirmBtn}
                                    disabled={!customInput.trim()}
                                >
                                    <Text style={styles.addTagConfirmText}>确定</Text>
                                </TouchableOpacity>
                            </View>
                        ) : (
                            <TouchableOpacity
                                onPress={() => setModalVisible(true)}
                                style={styles.addTagCircleBtn}
                            >
                                <Icon name="plus" size={20} color="#4CAF50" />
                            </TouchableOpacity>
                        )}
                    </View>
                </View>
                <TouchableOpacity style={styles.saveBtn} onPress={handleSave} disabled={saving}>
                    <Text style={styles.saveBtnText}>{saving ? '保存中...' : '保存'}</Text>
                </TouchableOpacity>
            </ScrollView>
            <Modal
                visible={modalVisible}
                transparent
                animationType="fade"
                onRequestClose={() => setModalVisible(false)}
            >
                <View style={styles.modalOverlay}>
                    <View style={styles.modalContent}>
                        <Text style={styles.modalTitle}>添加自定义标签</Text>
                        <TextInput
                            style={styles.modalInput}
                            placeholder="输入标签"
                            value={customInput}
                            onChangeText={setCustomInput}
                            autoFocus
                        />
                        <View style={styles.modalBtnRow}>
                            <TouchableOpacity
                                style={[styles.modalBtn, { backgroundColor: '#4CAF50' }]}
                                onPress={() => {
                                    if (customInput.trim()) {
                                        addCustomTag();
                                        setModalVisible(false);
                                    }
                                }}
                            >
                                <Text style={{ color: '#fff', fontWeight: 'bold' }}>确定</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[styles.modalBtn, { backgroundColor: '#eee' }]}
                                onPress={() => {
                                    setModalVisible(false);
                                    setCustomInput('');
                                }}
                            >
                                <Text style={{ color: '#333' }}>取消</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>
        </View>
    );
};

const styles = StyleSheet.create({
    container: { flex: 1, backgroundColor: '#fff' },
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 15,
        paddingTop: 40,
        paddingBottom: 10,
        backgroundColor: '#fff',
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
        justifyContent: 'space-between',
    },
    headerTitle: { fontSize: 20, fontWeight: 'bold', color: '#333' },
    groupBlock: { marginTop: 18, paddingHorizontal: 18 },
    groupTitle: { fontSize: 16, fontWeight: 'bold', color: '#333', marginBottom: 6 },
    subTitle: { fontSize: 14, color: '#666', marginBottom: 4, marginTop: 8 },
    subgroupBlock: { marginBottom: 6 },
    tagList: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
    tag: {
        borderWidth: 1,
        borderColor: '#4CAF50',
        borderRadius: 16,
        paddingHorizontal: 14,
        paddingVertical: 6,
        marginRight: 8,
        marginBottom: 8,
        backgroundColor: '#fff',
    },
    tagSelected: {
        backgroundColor: '#4CAF50',
        borderColor: '#4CAF50',
    },
    tagText: { color: '#4CAF50', fontSize: 14 },
    tagTextSelected: { color: '#fff' },
    customTag: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#e8f5e9',
        borderRadius: 16,
        paddingHorizontal: 12,
        paddingVertical: 5,
        marginRight: 8,
        marginBottom: 8,
    },
    customTagText: { color: '#388e3c', fontSize: 14 },
    addTagCircleBtn: {
        width: 36,
        height: 36,
        borderRadius: 18,
        backgroundColor: '#f2f2f2',
        justifyContent: 'center',
        alignItems: 'center',
        marginRight: 8,
        marginBottom: 8,
    },
    addTagInputRow: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#f2f2f2',
        borderRadius: 18,
        paddingHorizontal: 10,
        marginRight: 8,
        marginBottom: 8,
        height: 36,
    },
    addTagInputNew: {
        flex: 1,
        fontSize: 14,
        color: '#333',
        backgroundColor: 'transparent',
        borderWidth: 0,
        paddingVertical: 0,
        paddingHorizontal: 0,
    },
    addTagConfirmBtn: {
        marginLeft: 8,
        backgroundColor: '#4CAF50',
        borderRadius: 14,
        paddingHorizontal: 14,
        paddingVertical: 6,
    },
    addTagConfirmText: {
        color: '#fff',
        fontSize: 14,
        fontWeight: 'bold',
    },
    saveBtn: {
        backgroundColor: '#4CAF50',
        borderRadius: 24,
        margin: 30,
        paddingVertical: 12,
        alignItems: 'center',
    },
    saveBtnText: { color: '#fff', fontSize: 16, fontWeight: 'bold' },
    modalOverlay: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0,0.2)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    modalContent: {
        width: 280,
        backgroundColor: '#fff',
        borderRadius: 12,
        padding: 20,
        alignItems: 'center',
    },
    modalTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        marginBottom: 12,
    },
    modalInput: {
        width: '100%',
        borderWidth: 1,
        borderColor: '#ddd',
        borderRadius: 8,
        padding: 8,
        fontSize: 15,
        marginBottom: 18,
    },
    modalBtnRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        width: '100%',
    },
    modalBtn: {
        flex: 1,
        marginHorizontal: 5,
        borderRadius: 8,
        paddingVertical: 8,
        alignItems: 'center',
    },
});

export default PreferenceEdit;
